//
//  KDImageTextView.m
//  KD_3.0
//
//  Created by WangQiang on 15/10/9.
//  Copyright © 2015年 JunJun. All rights reserved.
//

#import "KDImageTextView.h"
#import "EmojiAttachment.h"
#import "NSAttributedString+EmojiText.h"
#import "NSString+EmojiAttribute.h"
@implementation KDImageTextView
#pragma mark -- 插入富文本(最顶层)
-(void)insertAttributeInCureLocation:(NSAttributedString *)attribute{
    if(!attribute) return;
    // 记录表情的插入位置
    NSUInteger insertIndex = self.selectedRange.location;
    // 插入表情图片到光标位置
    UIFont *preFont = self.font;
    UIColor *preColor = self.textColor;
    [self.textStorage insertAttributedString:attribute atIndex:insertIndex];
    //    // 让光标回到表情后面的位置
    self.selectedRange = NSMakeRange(insertIndex + attribute.length, 0);
    //恢复字体
    self.font = preFont;
    self.textColor = preColor;
}
#pragma mark --插入附件
-(void)insertAttachment:(NSTextAttachment *)attch{
    NSAttributedString *attachString = [NSAttributedString attributedStringWithAttachment:attch];
    [self insertAttributeInCureLocation:attachString];
}
//追加文字自动跳到顶部解决方法
//由系统滑动到顶部，再滑倒底部
//textView.layoutManager.allowsNonContiguousLayout = NO;
#pragma mark --插入表情
-(void)insertEmojiEmotion:(EmojiEmotion *)emoji{
    EmojiAttachment *attach = [EmojiAttachment emojiAttachmentWithEmotion:emoji];
    [self insertAttachment:attach];
}
#pragma mark -- 获取纯文本
-(NSString *)attrText{
    return self.attributedText.encodeEmojiText;
}

#pragma mark -- 复制粘贴监控
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender{
    if(action == @selector(select:)){
        return YES;
    }else if(action == @selector(copy:)){
        return YES;
    }else if(action == @selector(selectAll:)){
        return YES;
    }else if(action == @selector(cut:)){
        return YES;
    }else if(action == @selector(paste:)){//粘贴
        return YES;
    }else{
        return NO;
    }
}
-(void)cut:(id)sender{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
     [self.textStorage deleteCharactersInRange:self.selectedRange];
    self.selectedRange = NSMakeRange(self.selectedRange.location, 0);
    NSAttributedString *attr = [self.attributedText attributedSubstringFromRange:self.selectedRange];
    pasteboard.string = attr.encodeEmojiText;
    if([self.delegate respondsToSelector:@selector(textViewDidChange:)]){
        [self.delegate textViewDidChange:self];
    }
}
-(void)copy:(id)sender{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    NSAttributedString *attr = [self.attributedText attributedSubstringFromRange:self.selectedRange];
    pasteboard.string = attr.encodeEmojiText;
}
-(void)paste:(id)sender{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    [self insertAttributeInCureLocation:pasteboard.string.decodeEmojiAttribute];
}
@end
